from typing import Dict, List, Optional
from datetime import datetime
import asyncio
from ..adapters.akshare_adapter import (
    AKShareStockAdapter,
    AKShareFutureAdapter,
    AKShareETFAdapter,
    AKShareOptionAdapter
)
from ..utils.cache import LRUCache
from ..proto.data_service_pb2 import DataRequest, DataResponse

class DataAgent:
    """数据智能体核心模块"""
    
    def __init__(self):
        self.adapters = {
            'stock': AKShareStockAdapter(),
            'future': AKShareFutureAdapter(),
            'etf': AKShareETFAdapter(),
            'option': AKShareOptionAdapter()
        }
        self.cache = LRUCache(capacity=1000)
        self.data_quality_threshold = 0.95  # 数据质量合格阈值
        
    async def fetch_data(self, request: DataRequest) -> DataResponse:
        """智能数据获取入口"""
        cache_key = self._generate_cache_key(request)
        if cached := self.cache.get(cache_key):
            return self._wrap_response(cached, from_cache=True)
            
        # 智能路由选择数据源
        adapter = self._select_adapter(request.symbol)
        raw_data = await adapter.get_historical_data(
            request.symbol,
            request.start.ToDatetime(),
            request.end.ToDatetime()
        )
        
        # 数据质量检查
        if self._check_data_quality(raw_data):
            self.cache.put(cache_key, raw_data)
            return self._wrap_response(raw_data)
        else:
            return self._wrap_response([], error="数据质量不达标")
            
    def _select_adapter(self, symbol: str) -> object:
        """根据标的代码智能选择适配器"""
        if '.SH' in symbol or '.SZ' in symbol:
            return self.adapters['stock']
        elif '.CFE' in symbol:
            return self.adapters['future']
        elif 'IO' in symbol:
            return self.adapters['option']
        else:
            return self.adapters['etf']
            
    def _generate_cache_key(self, request: DataRequest) -> str:
        """生成缓存键（含数据版本）"""
        return f"{request.symbol}|{request.start}-{request.end}|v2"
        
    def _check_data_quality(self, data: List) -> bool:
        """检查数据完整性和合理性"""
        if len(data) < 10:
            return False
        # 检查关键字段完整性
        required_fields = ['open', 'high', 'low', 'close', 'volume']
        return all(field in data[0] for field in required_fields)
        
    def _wrap_response(self, data: List, error: str = "", from_cache: bool = False) -> DataResponse:
        """包装gRPC响应"""
        response = DataResponse()
        response.metadata.cache_hit = from_cache
        response.metadata.data_count = len(data)
        if error:
            response.error_message = error
        else:
            response.data.extend(data)
        return response

    async def monitor_quality(self):
        """定时数据质量监控任务"""
        while True:
            await asyncio.sleep(3600)  # 每小时检查一次
            for key in self.cache.keys():
                if not self._check_data_quality(self.cache.get(key)):
                    self.cache.evict(key)